package main

import (
	"embed"
	"flag"
	"io"
	"io/fs"
	"net/http"

	"file-view/backend"

	"github.com/gin-gonic/gin"
)

//go:embed front/out/*
var staticFS embed.FS

var (
	pluginDir string // 插件地址
	address   string
)

func main() {
	flag.StringVar(&pluginDir, "plugin", "./plugin/", "plugin directory")
	flag.StringVar(&address, "address", ":8080", "address")
	flag.Parse()

	router := gin.Default()
	// router.Use(gzip.Gzip(gzip.DefaultCompression))

	buildInController := backend.BuildInController{}
	initRouter(router, &buildInController, &backend.Router{}, &backend.FileController{})

	// 去掉 "front/out" 前缀，得到干净的 FS
	fsys, err := fs.Sub(staticFS, "front/out")
	if err != nil {
		panic(err)
	}
	// FIXME: 插件问题
	// router.Static("/plugin", pluginDir)

	// 用 http.FS 包装，并挂载到根路径
	router.StaticFS("/", http.FS(fsys))

	// 如果前端是 SPA（React/Next.js 导出），需要 fallback 到 index.html
	router.NoRoute(func(c *gin.Context) {
		file, err := fsys.Open("index.html")
		if err != nil {
			c.String(http.StatusNotFound, "index.html not found")
			return
		}
		defer file.Close()

		// 读取文件内容
		content, err := io.ReadAll(file)
		if err != nil {
			c.String(http.StatusInternalServerError, "failed to read index.html")
			return
		}

		// 返回内容
		c.Data(http.StatusOK, "text/html", content)
	})

	// router.NoRoute(func(c *gin.Context) {
	// 	fs := http.FS(fsys)
	// 	http.FileServer(fs).ServeHTTP(c.Writer, c.Request)
	// })

	loadedPlugins, err := LoadPlugins(router, pluginDir)
	if err != nil {
		panic(err)
	}
	buildInController.SetPluginInfo(loadedPlugins)

	err = router.Run(address)
	if err != nil {
		panic(err)
	}
}
